<template>
  <div class="classroomInfo">
    <!-- 筛选条件 -->
    <condition-card :label-width="'130px'" @reset="reset" @search="onSubmit">
      <el-row>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.name')">
            <el-input
              v-model="queryClassroomList.name"
              :placeholder="$t('message.plzSelect')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.department')">
            <DictSelect
              :plzSelect="true"
              v-model="queryClassroomList.departmentCode"
              :clearable="true"
              @change="handelCampusChang"
              :data="options.departmentCode"
            ></DictSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.type')">
            <DictSelect
              :plzSelect="true"
              v-model="queryClassroomList.type"
              :clearable="true"
              :data="options.roomTypes"
            ></DictSelect>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.campus')">
            <DictSelect
              :plzSelect="true"
              v-model="queryClassroomList.campus"
              :data="options.campus"
              :clearable="true"
              @change="handelCampusChang"
            ></DictSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.tower')">
            <DictSelect
              :plzSelect="true"
              v-model="queryClassroomList.towerCode"
              :clearable="true"
              :data="filterCondition.teachingBuildingArr"
              :filterable="true"
            ></DictSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.floor')">
            <el-input
              v-model="queryClassroomList.floor"
              :placeholder="$t('message.plzSelect')"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.usage')">
            <DictSelect
              :plzSelect="true"
              v-model="queryClassroomList.useing"
              :data="options.useing"
              :clearable="true"
              :exclude="usageExclude"
            ></DictSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.belongDepartment')">
            <DictSelect
              :plzSelect="true"
              v-model="queryClassroomList.dept"
              :data="options.dept"
              :clearable="true"
            ></DictSelect>
          </el-form-item>
        </el-col>
      </el-row>
    </condition-card>
    
    <!-- 基本信息列表 -->
    <el-card shadow="never">
      <div class="edu-opertion-bar">
        <div class="float-left">
          <el-input v-model="queryClassroomList.conditionValue" :placeholder="$t('classroomCheckTips.plzInputClassroomNameOrFloor')"
            suffix-icon="el-icon-search" style="width:240px" @keyup.enter.native="onSubmit" />
        </div>
        <div class="float-right">
          <el-button v-show="isAdmin" @click="exportClassroomInfo" >{{$t("message.export")}}</el-button>
          <el-dropdown @command="importRecord" v-show="isAdmin">
            <el-button type="primary">
              {{$t('message.import')}}
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="in">{{$t('message.import')}}</el-dropdown-item>
              <el-dropdown-item command="out">{{$t('message.down')}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button v-show="isAdmin" @click="openBatchEditDialog">{{$t("classroom.batchEdit")}}</el-button>
          <el-button v-show="isAdmin" type="primary" @click="openClassroomDialog">{{$t("classroom.creat")}}</el-button>
        </div>
        <div class="clear-both"></div>
      </div>
      
      <EduTable :order="false" :data="classroomList.data" :total="classroomList.total" :border="false"
        :pageNum="queryClassroomList.pageNum_" class="classroomTable" @page-change="pageChange" @selection-change="handleSelectionChange" >
        <el-table-column :label="$t('classroom.name')">
          <template slot-scope="props">
            <el-tooltip placement="top" :content="props.row.name" effect="light">
              <el-button type="text" @click="openClassroomDetails(props.row)">{{props.row.name}}</el-button>
            </el-tooltip>
        </template>
        </el-table-column>
        <el-table-column :label="$t('classroom.type')" min-width="80" show-overflow-tooltip>
          <template slot-scope="props">
              <span>{{props.row.typeI18n}}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('classroom.tower')" min-width="80" show-overflow-tooltip>
          <template slot-scope="props">
              <span>{{props.row.towerName}}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('classroom.campus')" show-overflow-tooltip>
          <template slot-scope="props">
              <span>{{props.row.campusI18n}}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('classroom.useDepartment')" min-width="80" show-overflow-tooltip>
          <template slot-scope="props">
              <!-- <span>{{props.row.departmentStr}}</span> -->
              <span :title="props.row.departmentStr.split('|').join('\n')" v-html="props.row.departmentShortStr"></span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('classroom.floor')" min-width="60">
          <template slot-scope="scope">{{scope.row.floor}}</template>
        </el-table-column>
        <el-table-column :label="$t('classroom.classCapacity')" min-width="50">
          <template slot-scope="scope">{{scope.row.classCapacity}}</template>
        </el-table-column>
        <el-table-column :label="$t('classroom.examCapacity')" min-width="50">
          <template slot-scope="scope">{{scope.row.examCapacity}}</template>
        </el-table-column>
        <el-table-column :label="$t('classroom.maxRow')" min-width="50">
          <template slot-scope="scope">{{scope.row.maxRow}}</template>
        </el-table-column>
        <el-table-column :label="$t('classroom.maxCol')" min-width="50">
          <template slot-scope="scope">{{scope.row.maxCol}}</template>
        </el-table-column>
        <el-table-column :label="$t('classroom.isClass')" min-width="50">
          <template slot-scope="scope">{{scope.row.isClass | getYesOrNo}}</template>
        </el-table-column>
        <el-table-column :label="$t('classroom.isExam')" min-width="50">
          <template slot-scope="scope">{{scope.row.isExam | getYesOrNo}}</template>
        </el-table-column>
        <el-table-column :label="$t('classroom.isBorrow')" min-width="50">
          <template slot-scope="scope">{{scope.row.isBorrow | getYesOrNo}}</template>
        </el-table-column>
        <el-table-column :label="$t('message.operating')" width="110" fixed="right">
          <template slot-scope="scope" >
            <el-button type="text" size="mini" @click="editClassroomInfo(scope.row)" v-if="scope.row.maintainable" >{{$t('message.edit')}}</el-button>
            <el-button type="text" size="mini" @click="deleteClassroomInfo(scope.row)" v-if="scope.row.maintainable" >{{$t('message.delete')}}</el-button>
          </template>
        </el-table-column>
      </EduTable>
    </el-card>
    <!-- 新建、修改教室信息弹窗 -->
    <edu-dialog ref="basicRoomInfo" :title="$t('classroom.basicRoomInfo')" class="systemDialog clearShaking"  @confirm="saveOrEdit" @close="closeClassroomDialog('classroomFrom')" >
      <el-form ref="classroomFrom" :model="classroomForm" :rules="classroomRules" label-position="right" label-width="120px" >
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.name')" prop="name">
              <el-input
                type="text"
                v-model="classroomForm.name"
                :placeholder="$t('message.plzSelect')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.nameEn')" prop="nameEn">
              <el-input
                type="text"
                v-model="classroomForm.nameEn"
                :placeholder="$t('message.plzSelect')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.campus')" prop="campus">
              <DictSelect
                :plzSelect="true"
                v-model="classroomForm.campus"
                :data="options.campus"
                :clearable="true"
                @change="handelCampusChang"
              ></DictSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.tower')" prop="towerCode">
              <DictSelect
                :plzSelect="true"
                v-model="classroomForm.towerCode"
                :clearable="true"
                :data="teachingBuildingArr"
              ></DictSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.type')" prop="type">
              <DictSelect
                :plzSelect="true"
                v-model="classroomForm.type"
                :clearable="true"
                :data="options.roomTypes"
              ></DictSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.floor')" prop="floor">
              <el-input
                type="text"
                v-model="classroomForm.floor"
                :placeholder="$t('message.plzSelect')"
                maxlength="5"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.classCapacity')" prop="classCapacity">
              <el-input
                type="text"
                v-model="classroomForm.classCapacity"
                :placeholder="$t('message.plzSelect')"
                maxlength="5"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.examCapacity')" prop="examCapacity">
              <el-input
                type="text"
                v-model="classroomForm.examCapacity"
                :placeholder="$t('message.plzSelect')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.maxRow')" prop="maxRow">
              <el-input
                type="text"
                v-model="classroomForm.maxRow"
                :placeholder="$t('message.plzSelect')"
                maxlength="5"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.maxCol')" prop="maxCol">
              <el-input
                type="text"
                v-model="classroomForm.maxCol"
                :placeholder="$t('message.plzSelect')"
                maxlength="5"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.isClass')" prop="isClass">
              <YesNoSelect v-model="classroomForm.isClass" :clearable="true"></YesNoSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.isExam')" prop="isExam">
              <YesNoSelect
                v-model="classroomForm.isExam"
                :labelAll="$t('message.plzSelect')"
                :clearable="true"
              ></YesNoSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.isBorrow')" prop="isBorrow">
              <YesNoSelect v-model="classroomForm.isBorrow" :clearable="true"></YesNoSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.usage')" prop="tempClassroomUsageList">
              <DictSelect
                :plzSelect="true"
                multiple="true"
                v-model="classroomForm.tempClassroomUsageList"
                :clearable="true"
                :data="options.useing"
                :exclude="usageExclude"
              ></DictSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.fixDepartment')" prop="tempFixDepartmentList">
              <DictSelect
                :plzSelect="true"
                multiple="true"
                v-model="classroomForm.tempFixDepartmentList"
                :clearable="true"
                :filterable="true"
                @change="handelTypeForFixDept"
                :data="options.fixedDept"
              ></DictSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.belongDepartment')" prop="tempBelongDepartmentList">
              <DictSelect
                :plzSelect="false"
                multiple="true"
                v-model="classroomForm.tempBelongDepartmentList"
                :clearable="true"
                :data="options.dept"
                :labelAll="$t('classroom.projectStr')"
              ></DictSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('classroom.remark')">
              <el-input type="textarea" :rows="3" v-model="classroomForm.remark"  maxlength="255" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </edu-dialog>
    <!-- 批量修改弹窗信息 -->
    <edu-dialog
      ref="batchEditDialog"
      :title="$t('classroom.batchEdit')"
      @close="closebatchEditDialog('batchEditFrom')"
    >
      <el-form
        ref="batchEditFrom"
        :model="batchEditFrom"
        :rules="classroomRules"
        label-position="right"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.isClass')" prop="isClass">
              <YesNoSelect v-model="batchEditFrom.isClass" :clearable="true"></YesNoSelect>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.isBorrow')" prop="isBorrow">
              <YesNoSelect v-model="batchEditFrom.isBorrow" :clearable="true"></YesNoSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('classroom.isExam')" prop="isExam">
              <YesNoSelect
                v-model="batchEditFrom.isExam"
                :labelAll="$t('message.plzSelect')"
                :clearable="true"
              ></YesNoSelect>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="buttons">
        <el-button @click="closebatchEditDialog('batchEditFrom')">{{$t('message.cancel')}}</el-button>
        <el-button type="primary" @click="batchEdit">{{$t('message.confirm')}}</el-button>
      </span>
    </edu-dialog>
    <!-- 教室详细信息 -->
    <edu-dialog
      ref="classroomDetailDialog"
      class="classroomDetailDialog"
      :title="$t('classroom.classroomDetail')"
      :showButtons="false"
    >
      <room-info-details :classroomDetail="classroomDetail" />
    </edu-dialog>

    <!-- 导入页面 -->
    <edu-dialog
      :title="$t('classroom.importClassroomTitle')"
      width="600px"
      ref="uploadDialog"
      @close="clearFiles"
      @confirm="uploadFile"
    >
      <el-form label-width="85px">
        <el-row>
          <el-form-item>
            <el-upload
              ref="upload"
              :data="{}"
              :on-success="uploadDone"
              :before-upload="beforeAvatarUpload"
              :before-remove="beforeRemove"
              :on-error="onError"
              :on-exceed="handleExceed"
              :multiple="false"
              :on-change="(file, fileList)=>{this.fileList = fileList}"
              :limit="1"
              :auto-upload="false"
              :accept="'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel'"
              :action="importUrl"
            >
              <el-button slot="trigger" size="small" type="primary">{{$t('label.selectFile')}}</el-button>
              <div slot="tip" class="el-upload__tip">{{$t('culture.profession.uploadXLSFileOnly')}}</div>
            </el-upload>
          </el-form-item>
        </el-row>
      </el-form>
    </edu-dialog>
  </div>
</template>

<script>
import { queryDic,findDeptForClassroom } from "common/src/api/dictionary";
import * as API from "common/src/api/resource/classroom";
import UTILS from "common/src/utils/utils";
import roomInfoDetails from "./components/roomInfoDetails";
import filters from "common/src/filters";
import mixin from 'common/src/mixins/index';
export default {
  name: "classroomInfo",
  mixins: [mixin],
  components: {
    roomInfoDetails
  },
  filters: {
    getYesOrNo(val) {
      return filters.yesOrNo(val);
    }
  },
  data() {
    const checkNumber = (rule, value, callback) => {
      let reg = /^(0|[1-9]\d*)$/;
      if (!(value+'')) {
        return callback(new Error(this.$t("message.inputRequired")));
      }
      if (!reg.test(value)) {
        callback(new Error(this.$t("validateMesagge.mustBeNumber")));
      } else callback();
    };
    return {
      // 筛选条件对象
      // 查询教室列表传参字段
      queryClassroomList: {
        pageNum_: 1,
        pageSize_: 20,
        name: "", // 教室名称
        departmentCode: "", // 部门
        type: "", //教室类型
        campus: "", // 校区
        towerCode: "", // 教学楼
        floor: "", // 楼层
        useing: "", // 用途
        dept:"",//所属部门
        conditionValue: "" // 教室名称/楼层查询
      },
      importUrl: API.uploadUrl,
      filterCondition: {
        teachingBuildingArr: []
      },
      // 下拉框数据
      options: {
        campus: [],
        departmentCode: [],
        roomTypes: [],
        useing: [], //用途
        fixedDept: [], // 固定使用部门 (学院)
        dept: [] // 所属部门
      },
      // isdisabled: true,//是否禁用
      isClassroomFlag: false, // 是否新建、编辑的标志
      isEdit: false, //false 为新增，true为编辑
      // 教室基本信息对象
      classroomForm: {
        name: "",
        nameEn: "", // 英文名称
        campus: "",
        code: "", // 教室代码
        towerCode: "",
        floor: "", //楼层
        type: "",
        classCapacity: "", // 排课容量
        maxRow: "", // 最大行
        examCapacity: "", // 排考容量
        isClass: "", // 是否可排课 '1'是 '0'否
        maxCol: "", // 最大列
        isBorrow: "", // 是否可借用 '1'是 '0'否
        isExam: "", // 是否可排考 '1'是 '0'否
        tempFixDepartmentList: [], // 固定使用部门
        tempBelongDepartmentList: [], // 所属部门
        tempClassroomUsageList: [], // 用途
        remark: "" // 备注
        
      },
      teachingBuildingArr: [],
      defaultTeachingBuildingArr:[],
      defaultCreateForm: {
        id: "",
        name: "",
        nameEn: "", // 英文名称
        campus: "",
        code: "", // 教室代码
        towerCode: "",
        floor: "", //楼层
        type: "",
        classCapacity: "", // 排课容量
        maxRow: "", // 最大行
        examCapacity: "", // 排考容量
        isClass: "", // 是否可排课 '1'是 '0'否
        maxCol: "", // 最大列
        isBorrow: "", // 是否可借用 '1'是 '0'否
        isExam: "", // 是否可排考 '1'是 '0'否
        tempFixDepartmentList: [], // 固定使用部门
        tempBelongDepartmentList: [], // 所属部门
        tempClassroomUsageList: [], // 用途
        remark: "" // 备注
      },
      selectionDatas: [],
      // 校验规则
      classroomRules: {
        name: [
          {
            required: true,
            message: this.$t("classroomCheckTips.plzInputClassroomName"),
            trigger: "blur"
          }
        ],
        campus: [
          {
            required: true,
            message: this.$t("classroomCheckTips.plzChooseCampus"),
            trigger: "change"
          }
        ],
        type: [
          {
            required: true,
            message: this.$t("classroomCheckTips.plzChooseClassroomType"),
            trigger: "change"
          }
        ],
        towerCode: [
          {
            required: true,
            message: this.$t("classroomCheckTips.plzChooseTower"),
            trigger: "change"
          }
        ],
        classCapacity: [
          { required: true, validator: checkNumber, trigger: "change" }
        ],
        floor: [{ required: true, validator: checkNumber, trigger: "blur" }],
        examCapacity: [
          { required: true, validator: checkNumber, trigger: "change" }
        ],
        maxRow: [{required: true, validator: checkNumber, trigger: "blur" }],
        maxCol: [{required: true, validator: checkNumber, trigger: "blur" }],
        isClass: [
          {
            required: true,
            message: this.$t("classroomCheckTips.plzChooseIsClass"),
            trigger: "change"
          }
        ],
        isBorrow: [
          {
            required: true,
            message: this.$t("classroomCheckTips.plzChooseIsBorrow"),
            trigger: "change"
          }
        ],
        isExam: [
          {
            required: true,
            message: this.$t("classroomCheckTips.plzChooseIsExam"),
            trigger: "change"
          }
        ],
        tempFixDepartmentList: [
          {
            required: true,
            message: this.$t("classroomCheckTips.plzChooseFixDept"),
            trigger: "change"
          }
        ],
        tempBelongDepartmentList: [
          {
            required: true,
            message: this.$t("classroomCheckTips.plzChooseBelongDept"),
            trigger: "change"
          }
        ],
        tempClassroomUsageList: [
          {
            required: true,
            message: this.$t("classroomCheckTips.plzChooseClassroomUsage"),
            trigger: "change"
          }
        ]
      },
      // 教室列表数据
      classroomList: {
        data: [],
        total: 0
      },
      // 批量修改数据
      batchEditFrom: {
        isClass: "",
        isBorrow: "",
        isExam: "",
        includeIds: []
      },
      selectDatas:[],
      batUpdateIds: [],
      // 教室详情
      classroomDetail: {},
      //是否为admin
      isAdmin:true,
      //排除教室用途为 排考、排课 借用专用的用途
      usageExclude:["05","06"]
    };
  },
  created() {
      // 初始化筛选条件下拉框数据
      this.getIsAdmin();
      this.initOptions();
      this.init();
      this.handelCampusChang(null);
      
    },
  methods: {
    getIsAdmin(){
      let mockerUser = this.$store.getters.getMockUser();
      let user = mockerUser ? mockerUser:this.$store.getters.getUser();
      let tempCurrentRole = user.currentRole;
      let tempInnerRoles = user.innerRoles;
      if (tempCurrentRole === "1" && (tempInnerRoles.includes("1") || tempInnerRoles.includes("2"))) {
        this.isAdmin = true;
      } else {
        this.isAdmin = false;
      }
    },
    //把部门list 转换成字符串
    getDepartmentStrByList(list) {
      let str = "";
      if (list != null) {
        list.forEach(index => {
          str += index.departmentCodeI18n + " |";
        });
        str = str.substr(0, str.length - 1);
      }
      return str;
    },
    //把用途list 转换成字符串
    getUsageStrByList(list) {
      let str = "";
      if (list != null) {
        list.forEach(index => {
          str += index.usageCodeI18n + " |";
        });
        str = str.substr(0, str.length - 1);
      }
      return str;
    },
    //把所属部门list 转换成字符串
    getProjectStrByList(list) {
      let str = "";
      if (list != null) {
        list.forEach(index => {
          str += index.projectIdI18n + " |";
        });
        str = str.substr(0, str.length - 1);
      }
      return str;
    },
    convertListStr(list) {
      if (!list)
        return "";
      if (list.length<=3){
        return list && list.length
          ? list
              .map(t => `${t.departmentCodeI18n}`)
              .reduce((a, b) => a +("<br>") + b)
          : "";
      }else{
        return this.convertListStr(list.slice(0,3))+"<br> ...";
      }
    },
    // 获取教室列表数据
    async init() {
      //数据转换 固定部门、用途、所属部门，让后台能够接受这些数据
      if (this.queryClassroomList.departmentCode) {
        this.queryClassroomList.fixDepartmentList = {
          departmentCode: this.queryClassroomList.departmentCode
        };
      }
      if (this.queryClassroomList.useing) {
        this.queryClassroomList.classroomUsageList = {
          usageCode: this.queryClassroomList.useing
        };
      } else {
        this.queryClassroomList.classroomUsageList = []
      }
      if (this.queryClassroomList.dept) {
        this.queryClassroomList.belongDepartmentList = {
          projectId: this.queryClassroomList.dept
        };
      }
      let res = await API.getClassroomBasalInfoList(this.queryClassroomList);
      if (res && res.code == 200) {
        // 对固定使用部门数据进行处理
        _.forEach(res.data.list, item => {
          item.departmentStr = this.getDepartmentStrByList(
            item.fixDepartmentList
          );
          item.usageStr = this.getUsageStrByList(item.classroomUsageList);
          item.projectStr = this.getProjectStrByList(item.belongDepartmentList);
          let tempfixDepartmentList = [];
          let tempbelongDepartmentList = [];
          let tempclassroomUsageList = [];
          item.fixDepartmentList.forEach(item => {
            if (item.departmentCode) {
              tempfixDepartmentList.push(item.departmentCode);
            }
          });
           //对使用部门进行缩短处理
           item.departmentShortStr = this.convertListStr(item.fixDepartmentList);
          item.fixDepartmentList = tempfixDepartmentList;
         
          item.belongDepartmentList.map(item => {
            if (item.projectId) {
               tempbelongDepartmentList.push(item.projectId);
            }
          });
          item.belongDepartmentList = tempbelongDepartmentList;
          item.classroomUsageList.map(item => {
             if (item.usageCode != null) {
             tempclassroomUsageList.push(item.usageCode);
            }
          });
          item.classroomUsageList = tempclassroomUsageList;
        });
        this.classroomList.data = res.data.list;
        this.classroomList.total = res.data.total_;
      }
    },
    //导出教室列表
    exportClassroomInfo() {
      let res = API.exportClassroomInfo(this.queryClassroomList);
    },
    // 分页功能
    pageChange(val) {
      this.queryClassroomList.pageNum_ = val.pageNum;
      this.queryClassroomList.pageSize_ = val.pageSize;
      this.init();
    },
    handleSelectionChange(val) {
      this.queryClassroomList.includeIds = val.map(item => {
        return item.id;
      });
      this.batchEditFrom.includeIds = val.map(item => {
        //如果该项数据可维护，添加到批量修改数据
        if (item.maintainable) {
          return item.id;
        }
      });
      this.selectDatas = val;
    },
    // 初始化筛选条件
    initFilterCondition() {
      this.queryClassroomList.pageNum_ = 1;
      this.queryClassroomList.pageSize_ = 20;
      this.queryClassroomList.name = "";
      this.queryClassroomList.departmentCode = "";
      this.queryClassroomList.type = "";
      this.queryClassroomList.campus = "";
      this.queryClassroomList.towerCode = "";
      this.queryClassroomList.floor = "";
      this.queryClassroomList.useing = "";
      this.queryClassroomList.dept = "";
      this.queryClassroomList.conditionValue = "";
      this.queryClassroomList.fixDepartmentList = [];
      this.queryClassroomList.belongDepartmentList = [];
      this.queryClassroomList.classroomUsageList = [];
      this.filterCondition.teachingBuildingArr = [];
    },
    // 获取下拉框数据（数据字典）
    initOptions() {
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_YX", "X_XQ", "X_JSLX", "X_GLBM", "X_JSYT"]
      };
      queryDic(data).then(res => {
        if (res.code == 200) {
          UTILS.fillSelect(
            {
              campus: "X_XQ",
              departmentCode: "X_YX",
              roomTypes: "X_JSLX",
              dept: "X_GLBM",
              useing: "X_JSYT"
            },
            res.data,
            this.options
          );
        }
      });
      findDeptForClassroom({isCourse:""}).then(res => {
        if (res.code == 200) {
          let dataMap = res.data;
          for (let key in dataMap) {
            this.options.fixedDept.push({
              value: key,
              label: dataMap[key],
              key: key //为element-ui 穿梭框提供唯一标识key字段所加,兼容以前数据处理格式
            });
          }
        }
      });
    },
    // 重置初始化筛选条件
    reset() {
      this.initFilterCondition();
      this.init();
      this.handelCampusChang(null);
    },
    onSubmit() {
      this.queryClassroomList.pageNum_ = 1;
      this.queryClassroomList.pageSize_ = 20;
      this.init();
    },
    // 新建、编辑教室
    saveOrEdit(info) {
      this.$refs["classroomFrom"].validate(valid => {
        if (valid) {
          if(this.global.isAcdemicDean) {
            if(this.classroomForm.type == 1) {
              this.$message({
                type: "warning",
                message: '学院教务员不能新增公共教室'
              });
              return;
            }
          }
          //数据转换 固定部门、用途、所属部门，让后台能够接受这些数据
          this.classroomForm.fixDepartmentList = this.classroomForm.tempFixDepartmentList.map(
            item => {
              return {
                departmentCode: item
              };
            }
          );
          this.classroomForm.belongDepartmentList = this.classroomForm.tempBelongDepartmentList.map(
            item => {
              return {
                projectId: item
              };
            }
          );
          this.classroomForm.classroomUsageList = this.classroomForm.tempClassroomUsageList.map(
            item => {
              return {
                usageCode: item
              };
            }
          );
          if (this.isEdit) {
            //修改教室
            API.updateClassroom(this.classroomForm).then(res => {
              if (res && res.code === 200) {
                this.$message({
                  type: "success",
                  message: this.$t("classroomResponseMessage.updateSuccess")
                });
                this.$refs.basicRoomInfo.close();
                this.queryClassroomList.includeIds = [];
                this.init();
              } else {
                this.$message({
                  type: "info",
                  message: response.msg
                });
              }
            });
          } else {
            //新增教室
            API.insertClassroom(this.classroomForm).then(res => {
              if (res && res.code === 200) {
                this.$message({
                  type: "success",
                  message: this.$t("classroomResponseMessage.addSuccess")
                });
                this.$refs.basicRoomInfo.close();
                this.queryClassroomList.includeIds = [];
                this.init();
              } else {
                this.$message({
                  type: "info",
                  message: response.msg
                });
              }
            });
          }
        }
      });
    },
    // 打开教室信息弹窗
    openClassroomDialog() {
      this.isClassroomFlag = true;
      this.$refs.basicRoomInfo.open();
    },
    //修改教室信息
    editClassroomInfo(data) {
      this.isEdit = true;
      this.isClassroomFlag = true;
      this.$refs.basicRoomInfo.open();
      let tempData = _.cloneDeep(data);
      tempData.teachingBuildingArr =[];
      this.handelCampusChang(tempData.campus);
      //为了让 这三个list 数据类型转化，防止数据类型变换造成 修改接口报错
      tempData.tempFixDepartmentList = tempData.fixDepartmentList;
      tempData.tempBelongDepartmentList = tempData.belongDepartmentList;
      tempData.tempClassroomUsageList = tempData.classroomUsageList;
      this.classroomForm = tempData;
    }, 
    // 获取教学楼数据方法 (根据校区获取)
    handelCampusChang(item = null) {
      if (this.isClassroomFlag) {
        this.classroomForm.towerCode = "";  
        this.teachingBuildingArr = [];
      } else {
        this.filterCondition.teachingBuildingArr = [];
        this.queryClassroomList.towerCode = "";
      }
      if (this.isClassroomFlag) {
        API.getTowerInfoByCampus({campus: item}).then(res => {
          if (res && res.code == 200) {
           let dataList = res.data;
           dataList.forEach(item => {
             this.teachingBuildingArr.push({
              value: item.code,
              label: item.name
            });
          });
         }
        });
     } else {
       //条件框教学楼受校区、部门联动 2019-12-04
       let params = {
         campus: this.queryClassroomList.campus,
         departmentCode: this.queryClassroomList.departmentCode,
       }
       API.conditionQueryByDict(params).then(res => {
         if (res && res.code == 200) {
           let dataList = res.data.list;
           dataList.forEach(item => {
             this.filterCondition.teachingBuildingArr.push({
              value: item.code,
              label: item.name
            });
          });
         }
        })
     } 
    },
    handelTypeForFixDept(val){
      //如果 国定使用部门包含 本科生院和研究生院，那么教室类型自动设置为公共类型
      if (val.includes('000015') || val.includes('000014')) {
        this.classroomForm.type = '1';
      } else {
        this.classroomForm.type = '0';
      }
    },
    deleteClassroomInfo(data) {
      let params = {
        id: data.id,
        code: data.code
      };
      this.$confirm(
        this.$t("message.deleteConfirm"),
        this.$t("message.confirm"),
        {
          distinguishCancelAndClose: false,
          confirmButtonText: this.$t("message.confirm"),
          cancelButtonText: this.$t("message.cancel")
        }
      ).then(() => {
        API.delClassroom(params).then(response => {
          if (response.code == 200) {
            this.$message({
              type: "success",
              message: this.$t("message.deleteSuccess")
            });
            this.queryClassroomList.includeIds = [];
            this.batchEditFrom.includeIds = [];
            this.selectDatas = [];
            this.init();
          } else {
            this.$message({
              type: "info",
              message: response.msg
            });
          }
        });
      });
    },
    //打开批量修改弹窗
    openBatchEditDialog() {
      if (this.batchEditFrom.includeIds.length == 0) {
        this.$alert(
          this.$t("common.pla.plsSelectRecord"),
          this.$t("message.prompt"),
          { type: "warning" }
        );
        return;
      }
      //判断是否选中的数据中有无权操作的数据
      let setlects = this.selectDatas;
      let flag = false;
      setlects.forEach(item => {
        if (!item.maintainable) {
          flag = true;
        }
      });
      if (flag) {
        this.$alert(
          "您选择的数据中有无权限操作的教室！",
          this.$t("message.prompt"),
          { type: "warning" }
        );
        return;
      }
      this.$refs.batchEditDialog.open();
    },
    // 关闭教室信息时触发
    closeClassroomDialog(ref) {
      //清楚表格数据
      this.$refs[ref].resetFields();
      this.classroomForm = JSON.parse(JSON.stringify(this.defaultCreateForm));
      this.teachingBuildingArr = this.defaultTeachingBuildingArr;
      this.isClassroomFlag = false;
      this.isEdit = false;
    },
    // 批量修改
    batchEdit() {
      this.$refs["batchEditFrom"].validate(valid => {
        if (valid) {
          API.batUpdateClassroom(this.batchEditFrom).then(res => {
            if (res && res.code === 200) {
              this.$message({
                type: "success",
                message: this.$t("classroomResponseMessage.batchEditsuccess")
              });
              this.queryClassroomList.includeIds = [];
              this.init();
              this.$refs.batchEditDialog.close();
            }
          });
        }
      });
    },
    // 关闭批量修改弹窗
    closebatchEditDialog(ref) {
      //清楚表格数据
      this.$refs[ref].resetFields();
      this.$refs.batchEditDialog.close();
    },
    // 打开查看教室详情
    openClassroomDetails(info) {
      this.$refs.classroomDetailDialog.open();
      let cloneInfo = _.clone(info);
      this.classroomDetail = cloneInfo;
    },
    //导入和下载模板
    importRecord(type) {
      if (type == "in") {
        this.$refs.uploadDialog.open();
      } else {
        window.location.href = API.downloadUrl;
      }
    },
    clearFiles() {
      this.$refs.upload.clearFiles();
      this.fileList = [];
    },
    uploadFile() {
      if (_.isEmpty(this.fileList)) {
        this.$message({
          type: "warning",
          message: this.$t("message.selectFilePlease")
        });
        return;
      }
      this.$refs.upload.submit();
      // 
    },
    beforeRemove(file, fileList) {
      this.$t("common.upload.remove") + ` ${file.name}？`;
    },
    handleExceed(files, fileList){
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeAvatarUpload(file) {
      let extName = file.name
        .substring(file.name.indexOf(".") + 1)
        .toLowerCase()
        .trim();
      if (extName !== "xls" && extName !== "xlsx") {
        this.$message({
          type: "error",
          message: this.$t("common.upload.unSupportesFileType")
        });
        this.clearFiles();
        return;
      }
      if (!(file.size / 1024 / 1024 < 3)) {
        this.$message({
          type: "error",
          message: this.$t("common.upload.sizeLimit3M")
        });
        this.clearFiles();
        return;
      }
    },
    uploadDone(res, file, fileList) {
      if (res.code == 200) {
        this.$message({
          type: "success",
          message: this.$t("common.tips.uploadSuccess")
        });
        this.queryClassroomList.includeIds = [];
        this.init();
        this.$refs.uploadDialog.close();
      } else {
        this.$message({
          type: "error",
          message: res.msg
        });
        this.clearFiles();
      }
    },
    onError(err, file, fileList) {
      let msg = JSON.parse(err.message);
      this.$message({
        type: "error",
        message: msg.message
      });
    }
  }
};
</script>

<style lang="scss">
.classroomInfo {
  .classroomDetailDialog {
    .el-dialog__footer {
      display: none;
    }
  }
  .classroomTable{
    .cell{
      white-space: pre-line;
	  padding: 0 2px;
	  text-align: center;
    }
  }
}
</style>